package flc.ast.fragment;

import android.app.Dialog;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.os.Handler;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.stark.irremote.lib.base.Category;
import com.stark.irremote.lib.base.IrUtil;
import com.stark.irremote.lib.base.bean.IrRemote;
import com.stark.irremote.lib.base.db.IrRemoteDbHelper;
import com.stark.irremote.lib.net.IRextReqManager;
import com.stark.irremote.lib.net.bean.IrCategory;

import java.util.ArrayList;
import java.util.List;

import flc.ast.AppConfig;
import flc.ast.R;
import flc.ast.activity.RemoteDActivity;
import flc.ast.activity.RemoteDsActivity;
import flc.ast.activity.RemoteDvdActivity;
import flc.ast.activity.RemoteDysonActivity;
import flc.ast.activity.RemoteFsActivity;
import flc.ast.activity.RemoteIPTVActivity;
import flc.ast.activity.RemoteJdhActivity;
import flc.ast.activity.RemoteJhqActivity;
import flc.ast.activity.RemoteJqrActivity;
import flc.ast.activity.RemoteKtActivity;
import flc.ast.activity.RemoteTyyActivity;
import flc.ast.activity.RemoteWlhzActivity;
import flc.ast.activity.RemoteYxActivity;
import flc.ast.activity.SelAddressActivity;
import flc.ast.activity.SelBrandActivity;
import flc.ast.adapter.AddRemoteAdapter;
import flc.ast.adapter.CategoryAdapter;
import flc.ast.adapter.RemoteAdapter;
import flc.ast.bean.MyCategoryBean;
import flc.ast.databinding.FragmentRemoteBinding;
import stark.common.basic.base.BaseNoModelFragment;
import stark.common.basic.event.EventStatProxy;
import stark.common.basic.retrofit.IReqRetCallback;
import stark.common.basic.view.container.StkRecycleView;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link RemoteFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class RemoteFragment extends BaseNoModelFragment<FragmentRemoteBinding> {

    private List<IrCategory> listRemotes = new ArrayList<>();
    private List<IrRemote> listAll=new ArrayList<>();
    private List<IrRemote> listShow=new ArrayList<>();
    private List<MyCategoryBean> listCategory = new ArrayList<>();
    private CategoryAdapter categoryAdapter;
    private RemoteAdapter remoteAdapter;
    private AddRemoteAdapter addRemoteAdapter;
    private int oldPosition;
    private boolean isEdit = false;
    private Dialog myAddRemoteDialog;
    private StkRecycleView dialogAddRemoteList;
    private String category="全部";


    @Override
    protected int onCreate() {
        return R.layout.fragment_remote;
    }

    @Override
    protected void initView() {
        EventStatProxy.getInstance().statEvent1(getActivity(), mDataBinding.event1Container);
        mDataBinding.ivAddRemote.setOnClickListener(this);
        mDataBinding.ivRemoteMore.setOnClickListener(this);
        mDataBinding.tvRemoteCancel.setOnClickListener(this);
        //遥控器类型
        mDataBinding.rvCategoryList.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
        categoryAdapter = new CategoryAdapter();
        mDataBinding.rvCategoryList.setAdapter(categoryAdapter);
        categoryAdapter.setOnItemClickListener(this);
        //我的遥控器
        mDataBinding.rvRemoteList.setLayoutManager(new GridLayoutManager(mContext, 2));
        remoteAdapter = new RemoteAdapter();
        mDataBinding.rvRemoteList.setAdapter(remoteAdapter);
        remoteAdapter.setOnItemClickListener(this);
        remoteAdapter.addChildClickViewIds(R.id.ivRemoteItemDelete);
        remoteAdapter.addChildClickViewIds(R.id.rlRemoteItem);
        remoteAdapter.setOnItemChildClickListener(this);
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.ivRemoteMore://遥控器处理
                isEdit = true;
                remoteAdapter.setEdit(true);
                remoteAdapter.notifyDataSetChanged();
                mDataBinding.ivRemoteMore.setVisibility(View.GONE);
                mDataBinding.tvRemoteCancel.setVisibility(View.VISIBLE);
                break;
            case R.id.tvRemoteCancel://取消处理
                cancelEdit();
                break;
            case R.id.ivAddRemote://添加遥控器
                if (!IrUtil.isSupportIr()) {
                    ToastUtils.showShort(R.string.your_device_not_infrared);
                    return;
                }
                //添加设备弹框
                addRemoteDialog();
                myAddRemoteDialog.show();
                break;
        }
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        if (adapter == categoryAdapter) {
            categoryAdapter.getItem(oldPosition).setSelect(false);
            categoryAdapter.notifyItemChanged(oldPosition);
            oldPosition = position;
            categoryAdapter.getItem(position).setSelect(true);
            categoryAdapter.notifyItemChanged(position);
            category=categoryAdapter.getItem(position).getName();
            getShow(categoryAdapter.getItem(position).getName());
            remoteAdapter.notifyDataSetChanged();
        } else if (adapter == addRemoteAdapter) {
            //(注:)机顶盒不是选择品牌而是选择地理位置
            if (addRemoteAdapter.getItem(position).id == Category.STB.getId()) {
                startActivity(SelAddressActivity.class);
            } else {
                gotoSelBrand(addRemoteAdapter.getItem(position).id);
            }
        }
    }

    @Override
    public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
        switch (view.getId()) {
            case R.id.ivRemoteItemDelete://删除
                showDialog(getString(R.string.delete_ing));
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        IrRemoteDbHelper.delete(remoteAdapter.getItem(position));
                        cancelEdit();
                        dismissDialog();
                    }
                }, 500);
                break;
            case R.id.rlRemoteItem:
                if (isEdit) return;
                gotoRemote(remoteAdapter.getItem(position));
                break;
        }
    }

    @Override
    protected void initData() {
        getDeviceData();
        getRemoteData();
    }

    private void getShow(String category){
        listShow.clear();
        if (category.equals("全部")){
            listShow.addAll(listAll);
        }
        for (IrRemote irRemote : listAll) {
            if (irRemote.categoryName.equals(category)){
                listShow.add(irRemote);
            }
        }
        remoteAdapter.setList(listShow);
        remoteAdapter.notifyDataSetChanged();
    }

    //去到对应遥控器界面
    private void gotoRemote(IrRemote bean) {
        if (bean.categoryId == Category.AIR_CONDITIONER.getId()) {
            RemoteKtActivity.isAdd = false;
            RemoteKtActivity.bean2 = bean;
            startActivity(RemoteKtActivity.class);
        } else if (bean.categoryId == Category.TV.getId()) {
            RemoteDsActivity.isAdd = false;
            RemoteDsActivity.bean2 = bean;
            startActivity(RemoteDsActivity.class);
        } else if (bean.categoryId == Category.STB.getId()) {
            RemoteJdhActivity.isAdd = false;
            RemoteJdhActivity.bean2 = bean;
            startActivity(RemoteJdhActivity.class);
        } else if (bean.categoryId == Category.NET_BOX.getId()) {
            RemoteWlhzActivity.isAdd = false;
            RemoteWlhzActivity.bean2 = bean;
            startActivity(RemoteWlhzActivity.class);
        } else if (bean.categoryId == Category.IPTV.getId()) {
            RemoteIPTVActivity.isAdd = false;
            RemoteIPTVActivity.bean2 = bean;
            startActivity(RemoteIPTVActivity.class);
        } else if (bean.categoryId == Category.DVD.getId()) {
            RemoteDvdActivity.isAdd = false;
            RemoteDvdActivity.bean2 = bean;
            startActivity(RemoteDvdActivity.class);
        } else if (bean.categoryId == Category.FAN.getId()) {
            RemoteFsActivity.isAdd = false;
            RemoteFsActivity.bean2 = bean;
            startActivity(RemoteFsActivity.class);
        } else if (bean.categoryId == Category.PROJECTOR.getId()) {
            RemoteTyyActivity.isAdd = false;
            RemoteTyyActivity.bean2 = bean;
            startActivity(RemoteTyyActivity.class);
        } else if (bean.categoryId == Category.AUDIO.getId()) {
            RemoteYxActivity.isAdd = false;
            RemoteYxActivity.bean2 = bean;
            startActivity(RemoteYxActivity.class);
        } else if (bean.categoryId == Category.LIGHT.getId()) {
            RemoteDActivity.isAdd = false;
            RemoteDActivity.bean2 = bean;
            startActivity(RemoteDActivity.class);
        } else if (bean.categoryId == Category.CLEANING_ROBOT.getId()) {
            RemoteJqrActivity.isAdd = false;
            RemoteJqrActivity.bean2 = bean;
            startActivity(RemoteJqrActivity.class);
        } else if (bean.categoryId == Category.AIR_CLEANER.getId()) {
            RemoteJhqActivity.isAdd = false;
            RemoteJhqActivity.bean2 = bean;
            startActivity(RemoteJhqActivity.class);
        } else if (bean.categoryId == Category.DYSON.getId()) {
            RemoteDysonActivity.isAdd = false;
            RemoteDysonActivity.bean2 = bean;
            startActivity(RemoteDysonActivity.class);
        }
    }


    //选择品牌
    private void gotoSelBrand(int id) {
        for (IrCategory bean : listRemotes) {
            if (bean.id == id) {
                SelBrandActivity.bean = bean;
            }
        }
        startActivity(SelBrandActivity.class);
    }

    //取消编辑
    private void cancelEdit() {
        isEdit = false;
        remoteAdapter.setEdit(false);
        remoteAdapter.notifyDataSetChanged();
        mDataBinding.ivRemoteMore.setVisibility(View.VISIBLE);
        mDataBinding.tvRemoteCancel.setVisibility(View.GONE);
    }

    //获取遥控器
    private void getDeviceData() {
        showDialog(getString(R.string.init_ing));
        IRextReqManager.init(AppConfig.IREXT_APP_KEY, AppConfig.IREXT_APP_SECRET, new IRextReqManager.IInitCallback() {
            @Override
            public void onInit(boolean success) {
                if (success) {
                    //初始化成功后再获取数据
                    IRextReqManager.irextApi().listCategories(null, new IReqRetCallback<List<IrCategory>>() {
                        @Override
                        public void onResult(boolean success, String msg, @Nullable List<IrCategory> result) {
                            dismissDialog();
                            if (result == null) {
                                ToastUtils.showShort(msg);
                                return;
                            }
                            //添加遥控器
                            listRemotes.addAll(result);
                            //遥控器类型
                            listCategory.clear();
                            listCategory.add(new MyCategoryBean("全部", true));
                            for (IrCategory irCategory : result) {
                                listCategory.add(new MyCategoryBean(irCategory.name, false));
                            }
                            categoryAdapter.setList(listCategory);
                        }
                    });
                } else {
                    dismissDialog();
                }
            }
        });
    }

    //获取我的遥控器
    private void getRemoteData() {
        IrRemoteDbHelper.getAllRemotes().observe(this, new Observer<List<IrRemote>>() {
            @Override
            public void onChanged(List<IrRemote> irRemotes) {
                if (irRemotes != null && irRemotes.size() > 0) {
                    listAll.clear();
                    listShow.clear();
                    listAll.addAll(irRemotes);
                    getShow(category);
                    mDataBinding.rvRemoteList.setVisibility(View.VISIBLE);
                } else {
                    mDataBinding.rvRemoteList.setVisibility(View.GONE);
                }
            }
        });
    }

    //添加设备弹框
    private void addRemoteDialog() {
        myAddRemoteDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_add_remote, null);
        myAddRemoteDialog.setContentView(inflate);
        myAddRemoteDialog.setCancelable(true);
        Window dialogWindow = myAddRemoteDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.BOTTOM);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 1.0);
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        dialogAddRemoteList = inflate.findViewById(R.id.rvDialogAddRemoteList);
        dialogAddRemoteList.setLayoutManager(new GridLayoutManager(mContext, 2));
        addRemoteAdapter = new AddRemoteAdapter();
        addRemoteAdapter.setList(listRemotes);
        dialogAddRemoteList.setAdapter(addRemoteAdapter);
        addRemoteAdapter.setOnItemClickListener(this);
    }

}